package com.hongyi.system.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.hongyi.common.framework.domain.JsonResult;
import com.hongyi.common.framework.domain.LoginBody;
import com.hongyi.common.framework.domain.LoginUser;
import com.hongyi.common.framework.domain.LoginVo;
import com.hongyi.common.framework.strategy.IAuthStrategy;
import com.hongyi.common.framework.utils.ValidatorUtils;
import com.hongyi.common.framework.validate.PasswordAuthGroup;
import com.hongyi.common.saToken.utils.LoginUtils;
import com.hongyi.system.service.IAuthService;
import com.hongyi.websocket.utils.WebSocketUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 身份认证接口
 *
 * @author DingHao
 */

@ApiSort(value = 2)
@Api( tags = "身份认证接口")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private IAuthService authService;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @ApiOperation("系统用户登录")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParam(name = "用户登录对象", value = "用户登录的对象", required = true, dataTypeClass = LoginBody.class)
    public JsonResult<LoginVo> login(@RequestBody LoginBody loginBody){
        //参数校验
        ValidatorUtils.validate(loginBody, PasswordAuthGroup.class);
        //策略模式登录
        LoginVo loginVo = IAuthStrategy.login(loginBody);
        Long userId = loginVo.getLoginUser().getUserId();
        scheduledExecutorService.schedule(() -> WebSocketUtils.sendMessage(userId, "欢迎登录Lychee后台管理系统"), 3, TimeUnit.SECONDS);
        return JsonResult.ok(loginVo);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息（角色与权限）
     */
    @ApiOperationSupport(order = 3)
    @GetMapping("/getInfo")
    public JsonResult<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginUtils.getLoginUser();
        Map<String, Object> map = new HashMap<>(3);
        map.put("user", loginUser);
        map.put("roles", loginUser.getRolePermission());
        map.put("permissions", loginUser.getMenuPermission());
        return JsonResult.ok(map);
    }

    /**
     * 退出登录
     *
     */
    @ApiOperationSupport(order = 2)
    @ApiOperation("退出登录")
    @SaIgnore
    @GetMapping("/logout")
    public JsonResult<Void> logout(){
        authService.logout();
        return JsonResult.ok("成功退出");
    }


}
